package com.chizha.iot.mqtt.simulator;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chizha.iot.mqtt.client.PushCallback;
import com.chizha.iot.mqtt.client.ServerMQTT;
import com.chizha.iot.mqtt.client.StubMQTT;
import com.chizha.iot.mqtt.hnhmsg.ViberSendMsg;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class HNHViberDetectGWY extends StubMQTT {
	public static final String TOPIC = "topic123";
	private static final String clientid = "StubMQTT1121";

	public static void main(String[] args) {
		
		
		HNHViberDetectGWY stub = new HNHViberDetectGWY();
		//String tmp = stub.genReportJson();
		//System.out.println(tmp);
		//ViberSendMsg vmsg = stub.parseConfigure(tmp);
		//System.out.println(vmsg.getMsgid());
		stub.start();
		return;
	}

	
	ViberSendMsg parseConfigure(String jsonstr)
	{
		ViberSendMsg tmp= (ViberSendMsg) JSON.parseObject(jsonstr,ViberSendMsg.class);
		return tmp;
	}
	public String genReportJson() {
		ViberSendMsg vvalue = new ViberSendMsg();
		vvalue.setMsgid(100);
		String sv = JSON.toJSONString(vvalue);
		return sv;
	}

	int counter;

	@Override
	public void run() {
		initialize(new PushCallbackMe(), clientid);
		message = new MqttMessage();
		message.setQos(0);
		message.setRetained(false);

		try {
			connect();
			String[] topicNames = getTopicName();
			for(String s:topicNames){
				System.out.println("topicName-------------"+s);
			}
           int[] Qos  = new int[topicNames.length];
           for(int i=0;i<topicNames.length;i++){
        	   Qos[i]=1;
           }
           String[] topic1 = topicNames;
           subscribeTopics(topic1, Qos);
		} catch (MqttSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("MQTT Stub Quit.");
			return;
		} catch (MqttException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("MQTT Stub Quit.");
			return;
		}
		/*while (true) {

			try {
				counter++;
				String payload = genReportJson();
				message.setPayload(payload.getBytes());
				sendTopic(TOPIC, message);
			} catch (MqttPersistenceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("MQTT send topic failed.");

			} catch (MqttException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("MQTT send topic failed.");
			}
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}*/
	}
	
	 private static String[] getTopicName() {
		   String sql = "select comm_id from customer_device_list where comm_id <> '' ";
		   List<Record> deviceList = new ArrayList<Record>();
		   deviceList = Db.find(sql);
		   
		   String[] topicName = new String[deviceList.size()];
		   for(int i = 0; i < deviceList.size(); i++){
			   String comm_id = deviceList.get(i).getStr("comm_id");
			   topicName[i] = "hnh/" + comm_id + "/down";
		   }
		   return topicName;
	   }


	class PushCallbackMe extends PushCallback {
		public void connectionLost(Throwable cause) {
			System.out.println("duankailianjie" + cause.getMessage());
		}

		public void deliveryComplete(IMqttDeliveryToken token) {
			// System.out.println("deliveryComplete---------" +
			// token.isComplete());
		}

		public void messageArrived(String topic, MqttMessage message)
				throws Exception {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        Calendar calendar1 = Calendar.getInstance();
		        String nowTime = sdf.format(calendar1.getTime());
				
				JSONObject msg = JSONObject.parseObject(new String(message.getPayload()));
				String comm_id = msg.getString("vid");
				
				String msgData = "{\"msgid\":1,\"vid\":\""+comm_id+"\",\"c\":\"ftpok\",\"time\":\""+nowTime+"\",\"ftpurl\":\"ftp://www.yanxinran.com/var/www/html/vdata/4000.bin\",\"uploadcause\":\"alarm\"}";
				topic = topic.replaceFirst("down", "up");
				System.out.println("msgData================:"+msgData);
				System.out.println("topic:==========="+topic);
				ServerMQTT server = new ServerMQTT(topic);
				server.message = new MqttMessage();
		        server.message.setQos(1);
		        server.message.setRetained(false);
		        server.message.setPayload(msgData.getBytes());
		        server.publish(server.topic11 , server.message);
				
				
				System.out.println("topic : " + topic);
				System.out.println("Qos : " + message.getQos());
				System.out.println("msg : " + new String(message.getPayload()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
